import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/model/leads.dart';
import 'package:yuan_hang_app/views/home/view/leads/adviser_select_page.dart';
import 'package:yuan_hang_app/widget/custom_search.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';
import '../../../../base/full_base_page.dart';
import '../../../../res/w_colors.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/common_attachment.dart';
import '../../../../widget/w_line.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_text.dart';
import 'leads_pool_detail_page.dart';

///线索池页面
class LeadsPoolPage extends StatefulWidget {
  final String? phone;
  const LeadsPoolPage({super.key, this.phone});

  @override
  BaseState<LeadsPoolPage> createState() => _LeadsPoolPageState();
}

class _LeadsPoolPageState extends BaseState<LeadsPoolPage> {
  List<Map> tabList = [
    {"title": "待转化"},
    {"title": "已转化"},
    {"title": "已失效"},
  ];

  List<Leads> dataList = [];

  int tabIndex = 0;
  Map sortParams = {};
  WListViewState? listState;
  int pageNum = 0;
  Map<String, dynamic> queryParams = {
    "current": 1,
    "size": 20,
  };


  String autoPhone = "";

  @override
  void initState() {
    if (widget.phone != null) {
      queryParams["nameOrPhone"] = widget.phone;
      autoPhone = widget.phone!;
    }
    super.initState();
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "线索池",
      child: Column(
        children: [
          CustomSearch(
            hintText: "客户名称/手机号",
            initText: autoPhone,
            onSortClick: () {
              WPopupWindow.showSort(
                  context: context,
                  sortType: SortType.LEADS_POOL,
                  sortParams: sortParams,
                  onSelected: (Map params) {
                    sortParams = params;
                    params.forEach((key, value) {
                      queryParams[key] = value;
                      if (queryParams.containsKey(key) && value == null) {
                        queryParams.remove(key);
                      }
                    });
                    //   print(params);
                    showLoading();
                    fetchDataList();
                  });
            },
            onTextChange: (text) {
              queryParams["current"] = 1;
              queryParams["nameOrPhone"] = text;
              CommonUtils.antiShake(fetchDataList);
            },
          ),
          Expanded(
              child: WListView(
            padding: EdgeInsets.only(top: 10.px),
            itemBuilder: _listItem,
            getDataList: (currentState, page) {
              listState = currentState;
              //  pageNum = page;
              queryParams["current"] = page;
              fetchDataList();
            },
          )),
        ],
      ),
    );
  }

  void fetchDataList() {
    HttpUtils(needLog: true)
        .post(Api.getCluePoolList, data: queryParams)
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data["records"] ?? [];
          List<Leads> list = data.map((item) => Leads.fromJson(item)).toList();
          listState?.onRefreshData(list, queryParams["current"]);
          if (queryParams["current"] == 1) {
            dataList.clear();
          }
          dataList.addAll(list);
        }
      } else {
        listState?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
      listState?.onFail(e);
    });
  }

  bool isSelected = false;

  Widget _listItem(context, index, dataList) {
    Leads item = dataList[index];

    String sexStr= CommonReqUtils.exchangeCodeToName(CommonReqUtils.sex, item.sex);
    if (sexStr.isNotEmpty) {
      sexStr = " • $sexStr";
    }

    return GestureDetector(
      onTap: () => {
        RouteHelper.pushWidget(context, LeadsPoolDetailPage(clueId: item.id!))
            .then((isSuccess) {
          queryParams["current"] = 1;
          fetchDataList();
        })
      },
      child: Container(
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
              color: WColors.CDFEFFB,
              offset: const Offset(0, 1),
              blurRadius: 3.px)
        ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
        margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        padding: EdgeInsets.only(right: 10.px, bottom: 10.px),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 5.px),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    color: WColors.primaryColor,
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.px),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Flexible(
                            flex: 1,
                            child: WText(
                              item.customerName ?? "",
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: WDimens.tsLarge,
                                  color: WColors.mainTextColor,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          Flexible(
                            flex: 2,
                            child: WText(
                              sexStr,
                              style: TextStyle(
                                  fontSize: WDimens.tsLarge,
                                  color: WColors.subTextColor),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  StatusBtn(
                    //  isTag: true,
                    isItemBtn: true,
                    height: 28.px,
                    text: CommonReqUtils.exchangeCodeToName(
                        CommonReqUtils.leaderSource, item.clueSource),
                    color: WColors.border,
                    fontColor: WColors.mainTextColor,
                    //   color: tagStyle["color"],
                  )
                ],
              ),
              WLine(
                height: 1.px,
                marginTop: 6.px,
                marginBottom: 6.px,
              ),
              Padding(
                padding: EdgeInsets.only(left: 10.px),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    WText(
                      item.phone ?? "",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      item.modelName ?? "",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      "线索创建： ${item.createdAt ?? ""} ",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.hintTextColor),
                    ),
                  ],
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  //   Expanded(child: Container()),
                  StatusBtn(
                    width:70.px,
                    height: 30.px,
                    isItemBtn: true,
                    isTag: true,
                    text: "抢线索",
                    fontSize: WDimens.tsMedium,
                    color: WColors.redMain,
                    icon: "ic_get_orders.png",
                    onPressed: () {
                      RouteHelper.pushWidget(
                          context,
                          AdviserSelectPage(
                            type: OperateType.snatchClue,
                            clueId: item.id,
                          )).then((value) {
                        queryParams["current"] = 1;
                        fetchDataList();
                      });
                    },
                  ),
                ],
              )
            ]),
      ),
    );
  }
}
